//
//  JEHNewsViewController.m
//  SinaNews
//
//  Created by 蒋恩浩 on 15/12/1.
//  Copyright © 2015年 JEH. All rights reserved.
//

#import "JEHNewsViewController.h"

@interface JEHNewsViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, passValue, presentViewController2>

@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) UIScrollView *titleScrollView;
@property (nonatomic, retain) NSMutableArray *titleArray;
@property (nonatomic, retain) NSMutableArray *lineArray;
@property (nonatomic, assign) NSInteger temp;
@property (nonatomic, retain) NSArray *titleUrlArray;
@property (nonatomic, retain) NSMutableArray *nameArray;
@property (nonatomic, retain) JEHDataBaseHandle *handle;
@property (nonatomic, retain) UIView *headerView;

@end

@implementation JEHNewsViewController

#pragma mark - memoryManagement
- (void)dealloc {
    
    [_nameArray release];
    [_handle release];
    [_headerView release];
    [_collectionView release];
    [_titleScrollView release];
    [_titleArray release];
    [_lineArray release];
    [_titleUrlArray release];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

#pragma mark - appear
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.alpha = 1;
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    if ([[user objectForKey:@"NightMode"] isEqualToString:@"Night"]) {
        
        self.tabBarController.tabBar.barTintColor = [UIColor blackColor];
    } else {
        self.tabBarController.tabBar.barTintColor = [UIColor colorWithRed:234 / 255.0 green:234 / 255.0 blue:234 / 255.0 alpha:1];
    }
    [self nightMode];
    [self.view nightMode];
    [self.collectionView nightMode];
    self.hidesBottomBarWhenPushed = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitleUrlArrayAndNameArray];
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, kHeaderHeight + 20)];
    [self setHeaderTitleView];
    [self createCollectionView];
    
#pragma mark - ReloadData
    NSNotificationCenter *centers = [NSNotificationCenter defaultCenter];
    [centers addObserver:self selector:@selector(receiveNotification:) name:@"ReloadData" object:nil];
    
    NSNotificationCenter *mineCenter = [NSNotificationCenter defaultCenter];
    [mineCenter addObserver:self selector:@selector(receiveNotification:) name:@"MineReloadData" object:nil];
}

#pragma mark - ReloadData
- (void)receiveNotification:(NSNotification *)notification {
    
    [self.headerView removeFromSuperview];
    [self setTitleUrlArrayAndNameArray];
    [self setHeaderTitleView];
    [self.collectionView reloadData];
}

#pragma mark - getData
- (void)setTitleUrlArrayAndNameArray {
    
    self.nameArray = [NSMutableArray arrayWithCapacity:0];
    self.titleUrlArray = [NSMutableArray arrayWithCapacity:0];
    self.handle = [JEHDataBaseHandle shareDataBaseHandle];
    [self.handle openDataBase];
    [self.handle selectTitleArrayAllFromDataBase];
    self.nameArray = self.handle.nameArray.copy;
    self.titleUrlArray = self.handle.urlArray.copy;
    [self.handle closeDataBase];
}

#pragma mark - createCollectionView
- (void)createCollectionView {
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(self.view.width, self.view.height - 20 - 44 - 5 - kHeaderHeight);
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 20 + kHeaderHeight, self.view.width, self.view.height - 20 - 44 - 5 - kHeaderHeight) collectionViewLayout:layout];
    [_collectionView release];
    [layout release];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.bounces = NO;
    _collectionView.pagingEnabled = YES;
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.backgroundColor = [UIColor whiteColor];
    [_collectionView registerClass:[JEHRootCollectionViewCell class] forCellWithReuseIdentifier:@"JEHRootCollectionViewCellIdentifier"];
    [self.view addSubview:self.collectionView];
}

#pragma mark - UICollectionViewDelegateMethod
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.titleUrlArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    JEHRootCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"JEHRootCollectionViewCellIdentifier" forIndexPath:indexPath];
    cell.tag = 1000;
    cell.titleUrl = self.titleUrlArray[indexPath.item];
    cell.delegate = self;
    return cell;
}

#pragma mark - setHeaderTitleView
- (void)setHeaderTitleView {
    
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, kHeaderHeight + 20)];
    [_headerView release];
    [self.view addSubview:self.headerView];
    CGFloat width = (self.view.width - kHeaderHeight) / 5;
    self.titleArray = [NSMutableArray arrayWithCapacity:0];
    self.lineArray = [NSMutableArray arrayWithCapacity:0];
    self.titleScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 20, self.view.width - kHeaderHeight, kHeaderHeight)];
    [_titleScrollView release];
    _titleScrollView.panGestureRecognizer.delaysTouchesBegan = YES;
    _titleScrollView.bounces = NO;
    _titleScrollView.showsHorizontalScrollIndicator = NO;
    _titleScrollView.contentSize = CGSizeMake(width * _nameArray.count, 0);
    for (int i = 0; i < _nameArray.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.tag = 100 + i;
        [button setTitle:_nameArray[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonPassAction:) forControlEvents:UIControlEventTouchUpInside];
        button.frame = CGRectMake(i * width, 0, width, kHeaderHeight);

        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(width / 4, button.bottom - 2, width / 2, 2)];
        if (i == 0) {
            [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            lineView.backgroundColor = [UIColor redColor];
        }
        [button addSubview:lineView];
        [lineView release];
        [self.titleScrollView addSubview:button];
        [self.titleArray addObject:button];
        [self.lineArray addObject:lineView];
    }
    [self.headerView addSubview:self.titleScrollView];
    _temp = 100;
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(self.view.width - kHeaderHeight, 20, kHeaderHeight, kHeaderHeight);
    [rightButton setImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(rightButtonPassAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:rightButton];
    
    CGFloat viewWidth = 0.1;
    for (int i = 0; i < 30; i++) {
        
        UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(self.view.width - kHeaderHeight - viewWidth * i, 20, viewWidth, kHeaderHeight)];
        rightView.backgroundColor = [UIColor grayColor];
        rightView.alpha = 0.05 - 0.001 * i;
        [self.headerView addSubview:rightView];
        [rightView release];
    }
}

- (CGFloat)getWidthWithText:(NSString *)text withFont:(CGFloat)font {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:font]};
    CGRect rect = [text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX,0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return rect.size.width;
}

#pragma mark - buttonPassAction
- (void)buttonPassAction:(UIButton *)sender {

    [sender setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    // 判断左右
    if (sender.tag > _temp) {
        // >3 偏移1
        if (sender.tag - 100 > 3 && sender.tag - 100 < self.titleArray.count - 1) {
            
            [self.titleScrollView setContentOffset:CGPointMake(sender.origin.x - 3 * sender.width, 0)];
        // 最后一个
        } else if (sender == self.titleArray[self.titleArray.count - 1]) {
            
            [self.titleScrollView setContentOffset:CGPointMake(sender.origin.x - 4 * sender.width, 0)];
        // <4
        } else {
            
            [self.titleScrollView setContentOffset:CGPointMake(0, 0)];
        }
        _temp = sender.tag;
    } else if (sender.tag < _temp) {
        if (sender.tag - 100 < self.titleArray.count - 4 && sender.tag - 100 > 0) {
            
            [self.titleScrollView setContentOffset:CGPointMake(sender.origin.x - sender.width, 0)];
        } else if (sender.tag - 100 > self.titleArray.count - 5) {
            
            [self.titleScrollView setContentOffset:CGPointMake((self.titleArray.count - 5) * sender.width, 0)];
        } else {
            
            [self.titleScrollView setContentOffset:CGPointMake(0, 0)];
        }
        _temp = sender.tag;
    }
    
    for (int i = 0; i < self.titleArray.count; i++) {
        
        UIButton *button = self.titleArray[i];
        if (sender.tag != button.tag) {
            
            [self.titleArray[i] setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            [self.lineArray[i] setBackgroundColor:[UIColor clearColor]];
        } else {
            [self.lineArray[i] setBackgroundColor:[UIColor redColor]];
        }
    }
    [self.collectionView setContentOffset:CGPointMake((sender.tag - 100) * self.view.frame.size.width, 0)];
    [self.collectionView reloadData];
}

#pragma mark - itemChangeAction
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

    NSInteger temp = self.collectionView.contentOffset.x / self.collectionView.width;
    UIButton *button = self.titleArray[temp];
    [self buttonPassAction:button];
}

#pragma mark - rightButtonAction
- (void)rightButtonPassAction:(UIButton *)sender {
    
    JEHMoreViewController *more = [[JEHMoreViewController alloc] init];
    CGFloat temp = self.collectionView.contentOffset.x / self.collectionView.width;
    more.temp = (NSInteger)temp;
    more.delegate = self;
    [self.navigationController pushViewController:more animated:YES];
    [more release];
}

- (void)passValueWithItem:(NSInteger)page {
    
    if (self.nameArray.count != 0) {
        
        if (page < self.nameArray.count) {
            
            [self buttonPassAction:self.titleArray[page]];
        } else {
            [self buttonPassAction:self.titleArray[0]];
        }
    }
}

- (void)passValueWithUrl:(NSString *)url withTitleName:(NSString *)title {
    
    [self.headerView removeFromSuperview];
    [self setHeaderTitleView];
    [self.collectionView reloadData];
}

#pragma mark - presentViewController2
- (void)passRootModelToDetail:(JEHRootModel *)rootModel {
    
    if (rootModel.picsModel.listArray.count == 0) {
        
        [self passRootModelToWebView:rootModel];
    } else {
        JEHDetailViewController *detail = [[JEHDetailViewController alloc] init];
        detail.rootModel = rootModel;
        [self presentViewController:detail animated:YES completion:^{
            
        }];
        [detail release];
    }
}

- (void)passRootModelToWebView:(JEHRootModel *)rootModel {

    JEHWebViewViewController *webView = [[JEHWebViewViewController alloc] init];
    webView.rootModel = rootModel;
    [self presentViewController:webView animated:YES completion:^{
    
    }];
    [webView release];
}

- (void)passRootModelToPlayerVC:(JEHRootModel *)rootModel {
    
    JEHSinglePlayerViewController *playerVC = [JEHSinglePlayerViewController shareSinglePlayerController];
    if (rootModel.videoModel.url.length == 0) {
        
        [self passRootModelToWebView:rootModel];
    } else {
        
        playerVC.player = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:rootModel.videoModel.url]];
    }
    [playerVC.player play];
    [self presentViewController:playerVC animated:YES completion:^{
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
